
;
/*
*使用 POPUP.alert(111111); POPUP.confirm(111111); POPUP.msg(111111);
*/
var POPUP = {
	i18n:{},
	index:0,
	zIndex:9999,
	canMov:false,
	mov:{x:0,y:0,left:0,top:0},
	options:{
		id:"popup-widget",
		title:'',
		content:'',
		timer:3000,
		shadeClose:false,
		position:'center',
		btn:[

		]
	},
	template: '<div class="modal on" data-modal>$shadeClose<div class="modal-content"><div class="modal-title">$title</div><span class="close" data-dismiss="modal"></span><div class="modal-text">$content</div>$buttons</div></div>',
	htmlToNode:function(htmlString){
		let parser = new DOMParser();
		let doc = parser.parseFromString(htmlString, 'text/html');
		return doc.body.firstElementChild;
	},
	initOptions:function(options){
		this.options = Object.assign(this.options, options);
	},
	getTemplate:function(){
		var template = document.getElementById('my-popup-template');
		if(template==null || typeof(template)=="undefined"){
			return this.template;
		}
		return template.innerHTML;
	},	
	alert:function(content, options){
		var that = this;
		options = typeof(options) == "undefined" ? {} : options;
		options['content'] = content;
		if(typeof(options["btn"])=="undefined"){
			var confirm_text = typeof(that.i18n["confirm"])!="undefined" ? that.i18n["confirm"] : '確認';
			options["btn"] = [confirm_text];
		}		
		this.open(options);
	},
	confirm:function(content, options){
		var that = this;
		options = typeof(options) == "undefined" ? {} : options;
		options['content'] = content;
		if(typeof(options["btn"])=="undefined"){
			var confirm_text = typeof(that.i18n["confirm"])!="undefined" ? that.i18n["confirm"] : '確認';
			var cancel_text = typeof(that.i18n["cancel"])!="undefined" ? that.i18n["cancel"] : '取消';
			options["btn"] = [confirm_text, cancel_text];
		}		
		this.open(options);
	},
	msg:function(content, options){
		var that = this;
		options = typeof(options) == "undefined" ? {} : options;
		options['content'] = content;		
		options = Object.assign({}, that.options, options);	
		that.open(options);
	},
	info:function(content, options){
		var that = this;
		options = typeof(options) == "undefined" ? {} : options;
		options['content'] = content;		
		options = Object.assign({}, that.options, options);	
		that.open(options);
		setTimeout(function() {
			that.close(options.index);
		}, options.timer);
	},
	open:async function(options){
		var that = this;
		options = typeof(options) == "undefined" ? {} : options;		
		options = Object.assign({}, this.options, options);
		if(typeof(options.url)!="undefined"){
			fetch(options.url).then((response)=>{
				return response.text();
			},(error)=>{
				console.log(err);
			}).then(data=>{
				options['content'] = data;
				that.renderAll(options);
			});
		}else{			
			that.renderAll(options);
		}
	},
	renderAll:function(options){
		var that = this;
		let shtml = that.renderContent(options);
		shtml = that.htmlToNode(shtml);
		that.resetOptions(shtml, options);
		that.registerEvent(shtml, options);
		that.index = that.index + 1;
		that.zIndex += 1;
		document.body.appendChild(shtml);
		that.resetPostion(shtml.querySelector(".modal-content"), options);
		shtml.style.zIndex = that.zIndex;
	},
	close:function(index){		
		var that = this;
		if(typeof(index)!="undefined"){
			document.querySelectorAll(".default-modal").forEach((item, itemIndex) => {
				if(item.getAttribute("index")==index){
					item.remove();
					that.canMov = false;
				}
			});
		}else{
			if(document.querySelector("[data-modal][index]")){
				document.querySelector("[data-modal][index]").remove();
			}
			that.canMov = false;
		}
	},
	renderContent:function(mergedObj){
		let template = this.getTemplate();
		let button_html = '';
		let shadeClose = '';
		if(mergedObj.btn.length >0){
			button_html += "<div class=\"modal-footer\">";
		}
		for (var x in mergedObj.btn) {
			let btn_id = Number(x)+1;
			button_html += "<button class='btn btn-default' filter='btn"+btn_id+"'>"+mergedObj.btn[x]+"</button>";
		}
		if(mergedObj.btn.length >0){
			button_html += "</div>";
		}
		if(mergedObj.title){
			mergedObj.title = '<h2>'+mergedObj.title+'</h2>';
		}
		if(mergedObj.shadeClose){
			shadeClose = "<div class='shade' data-dismiss='modal'></div>";
		}
		template = template.replace("$title", mergedObj.title);
		template = template.replace("$content", mergedObj.content);
		template = template.replace("$buttons", button_html);
		template = template.replace("$shadeClose", shadeClose);
		return template;
	}
	,resetOptions:function(shtml, options){
		var that = this;
		shtml.style.display = "block";
		shtml.setAttribute('id', that.options['id']+''+that.index);
		var old_class = shtml.getAttribute('class');
		if(typeof(options["class"])!="undefined"){
			shtml.attr('class', old_class + " "+options["class"]);
		}
		shtml.setAttribute('index', that.index);		
	}
	,registerEvent:function(shtml, options){
		var that = this;
		shtml.querySelectorAll("[data-dismiss]").forEach((item, index) => {
			item.addEventListener('click', function () {
				var parentWithModalAttr = this.closest('[data-modal]');
				    // 检查是否找到了元素，然后移除它
				if (parentWithModalAttr) {
					parentWithModalAttr.remove();
				}
			});
		});

		for (var x in options.btn) {
			let btn_id = Number(x)+1;
			let btn = shtml.querySelector("[filter='btn"+btn_id+"']");
			if(btn){
				btn.addEventListener('click', function(event) {
					if(typeof(options["btn"+btn_id])!="undefined"){
						options["btn"+btn_id]();
					}
					var parentWithModalAttr = this.closest('[data-modal]');
					if (parentWithModalAttr) {
						parentWithModalAttr.remove();
					}
				});
			}
		}
		let titleItem = shtml.querySelector(".modal-title");
		if(titleItem){
			titleItem.addEventListener("mousedown", function(e){
				let item = shtml.querySelector(".modal-content");
				that.canMov = true;
				that.mov.x = e.screenX;
				that.mov.y = e.screenY;
				that.mov.left = item.offsetLeft;
				that.mov.top = item.offsetTop;
			});
			titleItem.addEventListener("mousemove", function(e){
				if(that.canMov){
					let item = shtml.querySelector(".modal-content");
					var now_x = e.screenX,
					now_y = e.screenY,
					tl = that.mov.left,
					tt = that.mov.top;
					tl = now_x - that.mov.x + tl;
					tt = now_y - that.mov.y + tt;
					item.style.left = tl + "px";
					item.style.top = tt + "px";
				}
			});
		}
		document.addEventListener("mouseup", function(e){
			that.canMov = false;
			that.mov.x = 0;
			that.mov.y = 0;
			that.mov.left = 0;
			that.mov.top = 0;
		});
	},
	resetPostion:function(shtml, options){
		var that = this;
		if(typeof(options["area"]) != "undefined"){
			shtml.style.width = options["area"][0];
			shtml.style.height = options["area"][1];
		}
		if(options["position"]=='center'){
			var wx = window.innerWidth || document.documentElement.clientWidth,
			wy = window.innerHeight || document.documentElement.clientHeight,
			tw = that.outerWidth(shtml),
			th = that.outerHeight(shtml);
			var tl = (wx - tw) /2,
			tt = th > wy ? 0 : (wy - th)/2;
				//console.log({wx:wx, tw:tw, wy:wy, th:th});
			shtml.style.left = tl + "px";
			shtml.style.top = tt+"px";
		}else if( typeof(options["position"])=="Array"){
			shtml.style.left = options["position"][0];
			shtml.style.top = options["position"][1];
		}
	},
	outerWidth: function(element) {
		    // 获取元素的计算样式
		const style = window.getComputedStyle(element);
		
		    // 获取元素的宽度（内容区域宽度）
		const width = element.clientWidth;
		
		    // 获取左右边框的宽度
		const borderLeftWidth = parseFloat(style.borderLeftWidth);
		const borderRightWidth = parseFloat(style.borderRightWidth);
		
		    // 获取左右padding的宽度
		const paddingLeft = parseFloat(style.paddingLeft);
		const paddingRight = parseFloat(style.paddingRight);
		
		    // 计算总宽度（包括padding和border）
		return width + borderLeftWidth + borderRightWidth + paddingLeft + paddingRight;
	},
	outerHeight: function(element) {
		const rect = element.getBoundingClientRect();
		const style = window.getComputedStyle(element);
		
		const paddingTop = parseFloat(style.paddingTop);
		const paddingBottom = parseFloat(style.paddingBottom);
		const borderTop = parseFloat(style.borderTopWidth);
		const borderBottom = parseFloat(style.borderBottomWidth);
		
		const outerHeight = rect.height + paddingTop + paddingBottom + borderTop + borderBottom;
		return outerHeight;
	}
}